package common

import (
	"github.com/golang/protobuf/proto"
	"hundsun.com/hsl/hschain/common/types"
	"hundsun.com/hsl/hschain/common/util/pb"
	"hundsun.com/hsl/hschain/module"
	"hundsun.com/hsl/hschain/protos/config"
	"hundsun.com/hsl/hschain/store"
	dbm "hundsun.com/hsl/hschain/store/db"
)

// ConsensusModule 验证区块合法性
type ConsensusModule interface {
	module.Module

	CStatus() int32

	// IsActivited return whether the cosensus is active
	IsActivited() bool

	ConsensusSuspend() error

	ConsensusActive() error

	GetBaseClient() *BaseClient

	SetBaseClient(client *BaseClient)
}

// NewConsensusModule 新建一个consensus模块
func NewConsensusModule(name string) module.Module {
	create, err := LoadConsensus(name)
	if err != nil {
		panic("Load Consensus:[" + name + "] from manager failed.")
	}
	return create()
}

// NewGenesisConsensusModule 新建一个初始共识模块
func NewGenesisConsensusModule() module.Module {
	var consensusType string
	list := store.GetLedgerDB().NewList()
	_, conParamVals, err := list.ListPrefix(types.GeneConsensusUpdateKeyPrefix(), 1, dbm.OptionReverse|dbm.OptionWithValue)
	if len(conParamVals) > 0 {
		var conParam = &config.StepConParam{}
		err = proto.Unmarshal(conParamVals[0], conParam)
		if err != nil {
			panic(err.Error())
		}
		consensusType = conParam.GetConParam().GetType()
	} else {
		consensusType = pb.GetGenesisTransactionPayload().Consensus.Type
	}

	return NewConsensusModule(consensusType)
}
